package com.tangsm.api.demo.domain;

import com.tangsm.api.demo.enums.ResultCode;

import java.io.Serializable;

/**
 * API 返回体类
 * @author 湯神码
 * @date 2020/10/22
 */
public class Result<T> implements Serializable {
    /**
     * 业务状态码
     */
    private Integer code;
    /**
     * 信息描述
     */
    private String message;
    /**
     * 业务参数
     */
    private T data;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "Result{" +
                "code=" + code +
                ", message='" + message + '\'' +
                ", data=" + data +
                '}';
    }

    /**
     * 根据API枚举返回信息
     * @param resultCode
     * @param data
     */
    public Result(ResultCode resultCode, T data) {
        this.code = resultCode.getCode();
        this.message = resultCode.getMessage();
        this.data = data;
    }

    /**
     * 业务成功返回业务代码和描述信息
     * @return
     */
    public static Result<Void> success() {
        return new Result<Void>(ResultCode.SUCCESS, null);
    }

    /**
     * 业务成功返回业务代码,描述和返回的参数
     * @param data
     * @return
     */
    public static <T> Result<T> success(T data) {
        return new Result<T>(ResultCode.SUCCESS, data);
    }

    /**
     * 业务异常返回业务代码,描述
     * @param resultCode
     * @param <T>
     * @return
     */
    public static <T> Result<T> failure(ResultCode resultCode) {
        return failure(resultCode, null);
    }

    /**
     * 业务异常返回业务代码,描述和返回的参数
     */
    public static <T> Result<T> failure(ResultCode resultCode, T data) {
        if (resultCode == null) {
            return new Result<T>(ResultCode.BAD_REQUEST, null);
        }
        return new Result<T>(resultCode, data);
    }
}
